package com.shopping.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.shopping.impl.ShoppingCart;
import com.shopping.vo.CartItem;

public class GetShoppingCart extends HttpServlet {

	private static final long serialVersionUID = -8323504709964591329L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		HttpSession session = request.getSession();
		ShoppingCart cart = (ShoppingCart) session.getAttribute("shoppingcart");

		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>show Item</TITLE></HEAD>");
		out.println("  <BODY>");
		if (cart == null) {
			out.println("<h1>购物车中无商品<h1><br><br>");
			out.println("<a href='/test/displayItems.html'>选择商品</a><br><br>");
			return;
		} else {
			out.println("<h1>显示购购物车中商品信息<h1><br><br>");
			out.println("<a href='/test/displayItems.html'>添加商品</a><br><br>");
			printCartItem(out, cart);
		}
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	public void printCartItem(PrintWriter out, ShoppingCart cart) {
		ArrayList<CartItem> items = cart.getCart();
		CartItem item = null;
		out.println("<table>");
		out.println("<tr>");
		out.println("<td>商品编号</td>");
		out.println("<td>商品名称</td>");
		out.println("<td>单价</td>");
		out.println("<td>数量</td>");
		out.println("<td>价格小计</td>");
		out.println("</tr>");
		for (int i = 0; i < items.size(); i++) {
			item = items.get(i);
			out.println("<tr>");
			out.println("<td>" + item.getId() + "</td>");
			out.println("<td>" + item.getName() + "</td>");
			out.println("<td>" + item.getPrice() + "</td>");
			out.println("<td>" + item.getQuantity() + "</td>");
			out.println("<td>" + item.getSum() + "</td>");
			out.println("</tr>");
		}
		out.println("<tr><td colspan='5'>总计：" + cart.getTotal() + "元</td></tr>");
		out.println("</table>");

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}
